# Importing Data
TURKEY <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Lebanon/Turkey.xlsx")

# Checking the Imported Data
View(TURKEY)

# Creating Time Series Data
TURKEY_ts <- ts(TURKEY, start=c(2002,01), end=c(2019,07), frequency=12)

# Viewing and Checking the Created Time Series Data
TURKEY_ts
sum(is.na(TURKEY_ts))
library(forecast)
TURKEY_ts <- tsclean(TURKEY_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(TURKEY_ts)
plot(aggregate(TURKEY_ts,FUN=mean))

# Decomposing
TURKEY_ts_decomp <- decompose(TURKEY_ts)
plot(TURKEY_ts_decomp)

# Testing for Stationarity
acf(TURKEY_ts, lag.max=20)
pacf(TURKEY_ts, lag.max=20)

# To see any seasonal effect
boxplot(TURKEY_ts~cycle(TURKEY_ts))

# To remove trend effect
TURKEY_ts_diff <- diff(TURKEY_ts)
plot(TURKEY_ts_diff)

# To remove variance effect
TURKEY_ts_log <- log(TURKEY_ts)
plot(TURKEY_ts_log)

# To remove both (Trend and Variance) effects
TURKEY_ts_both <- diff(log(TURKEY_ts))
plot(TURKEY_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(TURKEY_ts, lag.max=20)
acf(log(TURKEY_ts), lag.max=20)
acf(diff(TURKEY_ts), lag.max=20)
acf(diff(log(TURKEY_ts)), lag.max=20)
pacf(TURKEY_ts, lag.max=20)
pacf(log(TURKEY_ts), lag.max=20)
pacf(diff(TURKEY_ts), lag.max=20)
pacf(diff(log(TURKEY_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
TURKEY_ts_model <- auto.arima(TURKEY_ts)
TURKEY_ts_model
TURKEY_ts_model <- auto.arima(TURKEY_ts, ic="aic", trace = TRUE)
TURKEY_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(TURKEY_ts_model$resid)
acf(TURKEY_ts_model$residuals, main='ACF Residual')
pacf(TURKEY_ts_model$residuals, main='ACF Residual')
Box.test(TURKEY_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
TURKEY_ts_forecast <- forecast (TURKEY_ts_model, level=c(95), h=257)
plot(TURKEY_ts_forecast)
TURKEY_ts_forecast             


write.table(TURKEY_ts_forecast, file="Turkey_TSA.csv", sep=",")
